//
//  ZQHttpTool.m
//  basketball_phone_lite
//
//  Created by Action on 15/5/20.
//  Copyright (c) 2015年 hzzq.com. All rights reserved.
//

#import "XCHttpTool.h"

@implementation XCHttpTool

+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 15.0;//设置请求超时时间
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            // time-consuming task
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [SVProgressHUD dismiss];
//            });
//        });
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}



+ (void)Post:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.0;//设置请求超时时间
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            // time-consuming task
//            dispatch_async(dispatch_get_main_queue(), ^{
//            });
//        });
        if (success) {
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


+ (void)Post:(NSString *)URLString parameters:(NSDictionary *)parameters ImageArr:(NSArray *)imageArr ImageName:(NSString *)imageName audioPath:(NSString *)audioPath audio:(NSString *)audio audioName:(NSString *)audioName success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // formData: 专门用于拼接需要上传的数据
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:
     ^void(id<AFMultipartFormData> formData) {
         
         if (imageArr.count != 0) {
             [imageArr  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                 [formData appendPartWithFileData:UIImageJPEGRepresentation(imageArr[idx] , 0.5)
                                             name:[NSString stringWithFormat:@"%@%ld",imageName,idx+1]
                                         fileName:@"image.jpg"
                                         mimeType:@"image/jpeg"];
             }];
             }
         
         if (audioPath !=nil) {
             NSData * audioData = [NSData dataWithContentsOfFile:audioPath];
             [formData appendPartWithFileData:audioData
                                         name:@"audio"
                                     fileName:@"audioName.mp3"
                                     mimeType:@"application/octet-stream"];
//             [formData appendPartWithFileURL:[NSURL URLWithString:audioPath]
//                                        name:@"audio"
//                                    fileName:@"audioName.mp3"
//                                    mimeType:@"application/octet-stream"
//                                       error:nil];
             
         }
    } success:^void(NSURLSessionDataTask * task, id responseObject) {
         if (success) {
             success(responseObject);
         }
     } failure:^void(NSURLSessionDataTask * task, NSError * error) {
 
         if (failure) {
             failure(error);
             
         }
     }];
}


+ (void)Post:(NSString *)URLString parameters:(NSDictionary *)parameters UIImage:(UIImage *)image ImageName:(NSString *)imageName audioPath:(NSString *)audioPath audio:(NSString *)audio audioName:(NSString *)audioName success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    // 1.创建网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // formData: 专门用于拼接需要上传的数据
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:
     ^void(id<AFMultipartFormData> formData) {
         if (image != nil) {
             [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.3)
                                         name:[NSString stringWithFormat:@"%@",imageName]
                                     fileName:@"image.jpg"
                                     mimeType:@"image/jpeg"];
         }
         if (audioPath !=nil) {
             NSURL* url = [NSURL fileURLWithPath:audioPath];
             
             NSData* recordData = [NSData dataWithContentsOfURL:url];
             [formData appendPartWithFileData:recordData
                                         name:@"audio"
                                     fileName:@"audioName.mp3"
                                     mimeType:@"application/octet-stream"];
         }
     } success:^void(NSURLSessionDataTask * task, id responseObject) {
         if (success) {
             success(responseObject);
         }
     } failure:^void(NSURLSessionDataTask * task, NSError * error) {

         if (failure) {
             failure(error);
         }
     }];
}

+ (void)downLoadVoiceWithURLStr:(NSString *)urlStr target:(void (^)(id))target  success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    //1.创建会话管理者
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];

    NSURL *url = [NSURL URLWithString:urlStr];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //2.下载文件
    /*
     第一个参数:请求对象
     
     第二个参数:progress 进度回调 downloadProgress
     
     第三个参数:destination 回调(目标位置)
     
     有返回值
     
     targetPath:临时文件路径
     
     response:响应头信息
     
     第四个参数:completionHandler 下载完成之后的回调
     
     filePath:最终的文件路径
     
     */
    
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        //监听下载进度
        
        //completedUnitCount 已经下载的数据大小
        
        //totalUnitCount     文件数据的中大小
        
//        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

//        NSLog(@"targetPath:%@",targetPath);
        
//        NSLog(@"fullPath:%@",fullPath);
        if (response) {
            target(fullPath);
        }

        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"success=====%@",filePath);
        if (success) {
            success(filePath);
        }
        if (failure) {
            failure(error);
        }
    }];

    //3.执行Task
    [download resume];
}


@end
